package org.vectrics.recruiter.struts;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;
import org.vectrics.html.menu.MenuTag;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.user.Person;
import org.vectrics.web.menu.MenuItem;

import com.hexacta.hrs.securitygroups.Permission;
import com.hexacta.hrs.securitygroups.SecurityGroup;

public class AdminMenuTag extends MenuTag {
	public static final long serialVersionUID = 70321975653298L;
	private transient final Logger log = Logger.getLogger(this.getClass());

	public AdminMenuTag() {
		super();
	}

	
	private Set findDomainsWithUserPrivilege(Person authPerson, String priv) {
		Set domains = new HashSet();
		if (authPerson != null) {
			domains.addAll(CoreServiceLocator.getPersonService().findDomainsWithUserPrivilege(authPerson, "company.create"));
		}
		return(domains);
	}
	
	/**
	 * Determina si un usuario tiene los permisios que requiere el item.
	 * @param menuItem, el item en cuestion.
	 * @return True si el usuario tiene permisos.
	 */
	private boolean userHavePermission(MenuItem menuItem){
		for(SecurityGroup group: this.getAuthPerson().getUser().getSecurityGroups()) {
    		for (Permission permission : group.getSecurityGroupRoles()) {
    			for (String permissionName: menuItem.getPermissions()) {
    				if (permissionName.equalsIgnoreCase(permission.getName().toString())) {
    					return true;
    				}
    			}
    		}
    	}
		return false;
	}
	
	/**
	 * Determines if a menu item will be displayed.  This method can be overridden 
	 * by derived class to hide certain menu items from user.
	 * @param The menu item in question.
	 * @return True if item can be displayed.
	 */
	protected boolean allowItemToBeDisplayed(MenuItem menuItem) {
		// Compruebo que tenga los permisos propios del menu.
		Boolean havePermission = userHavePermission(menuItem);
		
		//Si no tiene permiso, devuelvo false.
		if(!havePermission){
			return false;
		}
		
		//Si no tiene subMenus, devuelvo el booleano.
		if(!menuItem.getHasChildren()){
			return havePermission;
		}
		
		//Compruebo que tenga los permisos de al menos uno de sus submenues.
		MenuItem menuWithSubPermission = null;
        Iterator iter = menuItem.getChildList().iterator();
        while (iter.hasNext()) {
        	MenuItem subMenuItem = (MenuItem)iter.next();
            if(userHavePermission(subMenuItem)){
            	menuWithSubPermission = subMenuItem;
            }
        }
        
        //Si no tiene permisos para ningun submenu, devuelvo false.
        if(menuWithSubPermission == null){
        	return false;
        }

        //Busco el submenu por defecto
        MenuItem menuPorDefecto = null;
        Iterator iterator = menuItem.getChildList().iterator();
        while (iterator.hasNext()) {
        	MenuItem subMenuItem = (MenuItem)iterator.next();
            if(menuItem.getLink().equals(subMenuItem.getLink())){
            	menuPorDefecto = subMenuItem;
            	break;
            }
        }
        //Si no tengo permiso para el menu por defecto, pongo como valor por defecto del menu el action del primer submenu que tenga permisos.
		if(menuPorDefecto!= null && !userHavePermission(menuPorDefecto)){
			menuItem.setLink(menuWithSubPermission.getLink());
		}
		
    	return havePermission && (menuWithSubPermission != null);
    	
//		boolean result = true;
//		Person authPerson = ThreadProperties.getPerson();
//		
//		if (authPerson != null) {
//			if (child.getDescription().equals("menu.company.new")) {
//		
//				Set domainsWithRole = this.findDomainsWithUserPrivilege(authPerson, "company.create");
//				if (domainsWithRole.size() > 0)
//					result = true;
//			}
//			
//			if (child.getDescription().equals("menu.job.create")) {
//				result = false;
//			
//				Set domainsWithRole = this.findDomainsWithUserPrivilege(authPerson, "job.create");
//				if (domainsWithRole.size() > 0)
//					result = true;
//			}
//			
//			if (child.getDescription().equals("menu.person.new")) {
//				result = false;
//				Set domainsWithRole = this.findDomainsWithUserPrivilege(authPerson, "person.create");
//				if (domainsWithRole.size() > 0)
//					result = true;
//			}
//
//			if ((child.getDescription().equals("menu.content.mgr"))
//					|| (child.getDescription().equals("menu.site"))
//					) {
//				result = false;
//				UserPrivilegeType htmlChangePriv = CoreServiceLocator.getPersonService().findUserPrivilegeType("html.change"); 
//				if (authPerson.hasDomainOrGlobalPrivilege(htmlChangePriv, ThreadProperties.getDomain())) {
//					result = true;
//				}
//			}
//
//			if (child.getDescription().equals("menu.theme.select")) {
//				result = false;
//				boolean hostingModuleInstalled = RecruitServiceLocator.getRecruitConfiguration().getHostingModuleInstalled();
//				if (hostingModuleInstalled) {
//					UserPrivilegeType htmlChangePriv = CoreServiceLocator.getPersonService().findUserPrivilegeType("html.change"); 
//					if (authPerson.hasDomainOrGlobalPrivilege(htmlChangePriv, ThreadProperties.getDomain())) {
//						result = true;
//					}
//				}
//			}
//
//		
//		}
//				
//		if (log.isDebugEnabled())
//			log.debug("Menu item: " +  child.getDescription() + ", ok to display: " + result
//				 + "\r\n - menuItem.id=" + child.getId());
//		
//		return(result);
	}

}
